/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙，邂逅框架梦]
 * 
 * https://zhiqim.org/project/zhiqim_framework/zhiqim_kernel.htm
 *
 * Zhiqim Kernel is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package org.zhiqim.kernel.xml.parser;

import java.util.Collection;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.zhiqim.kernel.util.Classes;
import org.zhiqim.kernel.util.Strings;
import org.zhiqim.kernel.xml.Xml;
import org.zhiqim.kernel.xml.XmlParser;
import org.zhiqim.kernel.xml.Xmls;

/**
 * 列表解析器，和数组解析器类似
 *
 * @version v1.1.2 @author zouzhigang 2015-8-21 新建与整理
 */
public class ListParser implements XmlParser
{
    private Xml xmlMain;
    
    @Override
    public XmlParser set(Xml xmlMain)
    {
        this.xmlMain = xmlMain;
        return this;
    }

    @Override
    public String toStringInner(Object obj, String tagName, int tagLevel)
    {
        StringBuilder strb = new StringBuilder();
        if (tagName != null)
        {//要组号
            Strings.addNewLine(strb);
            Strings.addTwoSpace(strb, tagLevel);
            Xmls.addTagBegin(strb, tagName);
        }
        
        Collection<?> list = (Collection<?>)obj;
        for (Object o : list)
        {
            strb.append(xmlMain.toStringInner(o, tagName, tagLevel+1));
        }
        
        if (tagName != null)
        {//要组号
            Strings.addNewLine(strb);
            Strings.addTwoSpace(strb, tagLevel);
            Xmls.addTagEnd(strb, tagName);
        }
        
        return strb.toString();
    }

    @Override
    public Object toObjectInner(Node node, Class<?> clazz, Class<?> generics)
    {
        Collection<Object> list = Classes.newCollection(clazz);
        if (list == null)
        {//不支持的集合类型
            return null;
        }
        
        if (node == null || generics == null)
        {//没有该节点或没配置泛型不处理
            return list;
        }
        
        String tagName = Xmls.getXmlClassTag(generics);
        NodeList childList = node.getChildNodes();
        for (int i=0;i<childList.getLength();i++)
        {
            Node child = childList.item(i);
            if (child.getNodeType() != Node.ELEMENT_NODE)
                continue;
            
            if (!child.getNodeName().equals(tagName))
                continue;
            
            list.add(xmlMain.toObjectInner(child, generics, null));
        }
        
        return list;
    }
}
